package com.hy.movie.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.digest.MD5;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.movie.common.RedisKey;
import com.hy.movie.dao.OrderDao;
import com.hy.movie.model.bo.OrderBo;
import com.hy.movie.model.dto.OrderDto;
import com.hy.movie.model.entity.Order;
import com.hy.movie.service.OrderService;
import com.hy.movie.wxpay.WxPreOrderResponse;
import com.hy.movie.wxpay.service.WxPlaceOrderService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private WxPlaceOrderService wxPlaceOrderService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Value("${wxmini.appId}")
    private String appId;
    @Value("${wxmini.matchId}")
    private String matchId;
    @Value("${wxmini.secret}")
    private String secret;
    @Override
    public OrderBo placeOrder(OrderDto orderDto, String token) throws Exception {
        Order order = new Order();
        BeanUtils.copyProperties(orderDto,order);
        order.setIsPay(0);
        orderDao.insert(order);
        OrderDto wxOrderDto=new OrderDto();
        wxOrderDto.setSign(null);
        wxOrderDto.setVendor(null);
        ObjectMapper objectMapper = new ObjectMapper();
        String json = objectMapper.writeValueAsString(wxOrderDto);

        String result = stringRedisTemplate.opsForValue().get(RedisKey.WX_SESSION_ID.replace("{sessionId}", token));
        String openId = result.split("#")[1];
        WxPreOrderResponse wxPreOrderResponse = wxPlaceOrderService.placeOrder(order, openId);
        OrderBo orderBo = new OrderBo();
        orderBo.setPrepay_id(wxPreOrderResponse.getPrepay_id());
        orderBo.setTimeStamp(order.getBuyTime().toString());
        String random = RandomUtil.randomString(10);
        orderBo.setNonceStr(random);
        StringBuilder sb=new StringBuilder();
        sb.append("appid=").append(appId).append("&body=").append(json).append("&mch_id=").append(matchId).append("&nonce_str=").append(random);
        String stringSignTemp=sb+"&key="+secret;
        String md5Str = SecureUtil.md5(stringSignTemp);
        md5Str = md5Str.toUpperCase();
        orderBo.setPaySign(md5Str);
        return orderBo;
    }
}
